from annoying.decorators import render_to
from django.shortcuts import redirect
from django.http import HttpResponse
from django.utils import simplejson
from django.db.models import Count

from core.extensions.decorators import login_required

from core.models import User, City, Event
from core.forms import ProfileForm, CityForm


@login_required()
@render_to('profile/details.html')
def details(request):
    recomendations_by_cost = None
    recomendations_by_participants = None
    user = User.objects.get(id=request.session['user_id'])
    events = Event.objects.filter(status=Event.Status.Scheduled, \
                                  city__in=user.cities.all()).exclude(participants=user)
    recomendations_by_cost = events.order_by('-current_sum_for_user')
    recomendations_by_participants = events.annotate(participants_count=Count('participants')).order_by('-participants_count')
    return {'recomendations_by_cost': recomendations_by_cost, \
            'recomendations_by_participants': recomendations_by_participants}


@login_required()
@render_to('profile/edit.html')
def edit(request):
    user = User.objects.get(id=request.session['user_id'])
    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES, instance=user)
        if form.is_valid():
            form.save()
            return redirect(details)
    else:
        form = ProfileForm(instance=user)
    city_form = CityForm(cities=user.cities.all().values_list('id', flat=True))
    cities = user.cities.all()
    return {'form': form, 'city_form': city_form, 'cities': cities}


def add_city(request):
    if request.is_ajax():
        response_string = request.POST['data']
        city_id = response_string[response_string.find('=') + 1:]
        city_name = City.objects.get(id=city_id).name
        
        user = User.objects.get(id=request.session['user_id'])
        user.cities.add(city_id)
        user.save()
        return HttpResponse(simplejson.dumps({'city_id': city_id, 'city_name': city_name}), mimetype='application/json')


def remove_city(request):
    if request.is_ajax():
        city_id = request.POST['cityid']
        city_name = City.objects.get(id=city_id).name
        
        user = User.objects.get(id=request.session['user_id'])
        user.cities.remove(city_id)
        user.save()

        filtered = list(City.objects.order_by('name').exclude(id__in=user.cities.all()).values_list('id', flat=True))
        city_index = filtered.index(int(city_id))
        insertAfter = -1
        if city_index != 0:
            insertAfter = filtered[city_index - 1]
            
        return HttpResponse(simplejson.dumps({'insertAfter': insertAfter, 'city_name': city_name}), mimetype='application/json')
